import { Pipe, PipeTransform } from '@angular/core';
import { find, has, isArray, isEmpty, isEqual, isObject } from 'lodash';

/**
 * 根据字典，key转换成value
 */
@Pipe({
  name: 'dict'
})
export class DictPipe implements PipeTransform {

  transform(value: any, ...args: any[]): any {
    if (isEmpty(args)) {
      return value;
    }

    if (args[0] instanceof Map) {
      return args[0].get(value);
    }

    if (isArray(args[0])) {
      const k = args[1] ? args[1] : 'key';
      const v = args[2] ? args[2] : 'value';

      const ret: any = find(args[0], (i: any) => isEqual(value, i[k]));
      if (ret) {
        return ret[v];
      }
    }

    if (isObject(args[0]) && has(args[0], value)) {
      return args[0][value];
    }


    return value;
  }
}
